<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item prop="key">
        <el-select @change="changeKeyType" v-model="queryParamsSearch.key" placeholder="" style="width: 120px;">
          <el-option v-for="item in keyList" :value="item.value" :label="item.label" :key="item.label"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="" prop="keyWord" style="margin-left: -34px;">
        <el-input style="width:200px;border-radius: 0;"
                  v-model="queryParamsSearch.keyWord"
                  placeholder="请输入内容"
                  clearable
                  @keyup.enter="handleQuery"
                  :disabled="!singleSearch"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="changeSearchType" plain :type="singleSearch?'':'primary'">高级</el-button>
      </el-form-item>
      <div v-show="!singleSearch">
        <el-form-item label="设备序列号" prop="serialNumber" >
          <el-input style="width:200px;border-radius: 0;"
                    v-model="queryParams.serialNumber"
                    placeholder="请输入设备序列号"
                    clearable
                    @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="MAC地址" prop="macAddress" >
          <el-input style="width:200px;border-radius: 0;"
                    v-model="queryParams.macAddress"
                    placeholder="请输入MAC地址"
                    clearable
                    @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="设备品牌" prop="deviceBrand" >
          <el-input style="width:200px;border-radius: 0;"
                    v-model="queryParams.deviceBrand"
                    placeholder="请输入设备品牌"
                    clearable
                    @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="设备型号" prop="deviceModel" >
          <el-input style="width:200px;border-radius: 0;"
                    v-model="queryParams.deviceModel"
                    placeholder="请输入设备型号"
                    clearable
                    @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item label="辖区" prop="areaName">
          <el-input style="width:200px;"
                    v-model="queryParams.areaName"
                    placeholder="请输入辖区"
                    clearable
                    @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="街道" prop="streetName">
          <el-input style="width:200px;"
                    v-model="queryParams.streetName"
                    placeholder="请输入街道"
                    clearable
                    @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="社区" prop="community">
          <el-input style="width:200px;"
                    v-model="queryParams.community"
                    placeholder="请输入社区"
                    clearable
                    @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="小区" prop="residentialName">
          <el-input style="width:200px;"
                    v-model="queryParams.residentialName"
                    placeholder="请输入小区"
                    clearable
                    @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="设备状态" prop="deviceStatus">
          <el-select v-model="queryParams.deviceStatus" placeholder="请选择设备状态" clearable
                     style="width: 200px">
            <el-option
                v-for="dict in wvp_device_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            />
          </el-select>
        </el-form-item>
      </div>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['wvp:cardReader:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['wvp:cardReader:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['wvp:cardReader:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="Upload" @click="handleImport"
                   v-hasPermi="['wvp:cardReader:import']">导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain @click="beginPushType"
                   v-hasPermi="['wvp:cardReader:pushTypeBatch']">推送状态
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['wvp:cardReader:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table ref="tableRef" :height="tableHeight" v-loading="loading" :data="cardReaderList"
              @selection-change="handleSelectionChange">
      <el-table-column min-width="120px " type="selection" width="55" align="center" fixed="left"/>
      <el-table-column min-width="60px " type="index" label="序号" width="55" align="center" fixed="left"/>
      <el-table-column min-width="120px " label="设备序列号" align="center" prop="serialNumber" fixed="left"/>
      <el-table-column min-width="120px " label="运行状态" align="center" fixed="left">
        <template #default="scope">
          <dict-tag :options="wvp_device_status" :value="scope.row.deviceStatus"/>
        </template>
      </el-table-column>
      <el-table-column min-width="120px " label="设备品牌" align="center" prop="deviceBrand"/>
      <el-table-column min-width="120px " label="设备型号" align="center" prop="deviceModel"/>
      <el-table-column min-width="120px " label="投放点名称" align="center" prop="deviceName"/>

      <el-table-column min-width="120px " label="MAC地址" align="center" prop="macAddress"/>
      <el-table-column min-width="120px " label="辖区" align="center" prop="areaName"/>
      <el-table-column min-width="120px " label="街道" align="center" prop="streetName"/>
      <el-table-column min-width="120px " label="社区" align="center" prop="community"/>
      <el-table-column min-width="120px " label="小区" align="center" prop="residentialName"/>
      <!--      <el-table-column min-width="120px " label="地址" align="center" prop="address" />-->
      <!--      <el-table-column min-width="120px " label="投放点" align="center" prop="placement" />-->


      <el-table-column min-width="120px " label="登记时间" align="center" prop="registerTime" width="180">

      </el-table-column>
      <el-table-column min-width="120px " label="修改人" align="center" prop="updateBy"/>
      <el-table-column min-width="120px " label="修改时间" align="center" prop="updateTime" width="180">

      </el-table-column>
      <el-table-column min-width="120px " label="接入状态" align="center" prop="accessStatus">
        <template #default="scope">
          {{ scope.row.accessStatus === 0 ? '未接入' : '已接入' }}
        </template>
      </el-table-column>
      <el-table-column min-width="120px " label="接入时间" align="center" prop="accessTime" width="180">
      </el-table-column>

      <el-table-column min-width="120px " label="备注" align="center" prop="remark"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right"
                       min-width="160px;" prefix="right">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['wvp:cardReader:edit']">修改
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['wvp:cardReader:remove']">删除
          </el-button>
          <el-button v-hasPermi="['wvp:cardReader:pushType']">是否推送
            <el-switch :active-value="1" :inactive-value="0" v-model="scope.row.pushType" readonly
                       @click="changePushType(scope.row)"></el-switch>
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <plugin-form ref="pluginFormRef" @close="close"></plugin-form>


    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
                 :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
                 :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <el-icon class="el-icon--upload">
          <upload-filled/>
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>

        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
              <el-checkbox v-model="upload.updateSupport"/>
              是否更新已经存在的读卡器数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                     @click="importTemplate">下载模板
            </el-link>
          </div>
        </template>
      </el-upload>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="批量修改推送状态" v-model="showPushTypeForm" width="400px" append-to-body>
      <el-form ref="cardReaderRef" :model="pushTypeForm" :rules="rules" label-width="100px" class="m-form-inline"
               inline>
        <div style="padding-left: 36px;padding-bottom: 10px;font-size: 18px;">已勾选<span style="color: #c45656">{{ pushTypeForm.ids.length }}</span>条数据</div>
        <el-form-item label="推送状态" prop="pushType">
          <el-select v-model="pushTypeForm.pushType" style="width:200px">
            <el-option :value="0" label="不推送"></el-option>
            <el-option :value="1" label="推送"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitPushTypeFormHandle">确 定</el-button>
          <el-button @click="showPushTypeForm = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="CardReader">
import PluginForm from './components/Form.vue'
import {listCardReader, updateCardReader, delCardReader,submitPushTypeForm} from "@/api/wvp/cardReader";
import {getToken} from "@/utils/auth";

const pluginFormRef = ref()
const {proxy} = getCurrentInstance();
const {wvp_device_status} = proxy.useDict('wvp_device_status');
const cardReaderList = ref([]);

const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const singleSearch = ref(true)
function resetMyForm(){
  queryParams.value={
    pageNum: 1,
    pageSize: 10,
    deviceBrand: null,
    deviceModel: null,
    deviceStatus: null,
    deviceName: null,
    serialNumber: null,
    proviceName: null,
    proviceCode: null,
    cityName: null,
    cityCode: null,
    areaName: null,
    areaCode: null,
    address: null,
    community: null,
    residentialName: null,
    ip: null,
    macAddress: null,
    placement: null,
    registerTime: null,
    accessStatus: null,
    accessTime: null,
    streetName: null,
    streetCode: null
  }
}
function changeSearchType(){
  proxy.resetForm("queryRef");
  resetMyForm();
  queryParamsSearch.value.keyWord='';
  singleSearch.value=!singleSearch.value;
  nextTick(()=>{
    handleResize()
  })
}

const queryParamsSearch = ref({
  key: "serialNumber",
  keyWord: ""
})
const keyList = reactive([
  {label: "设备序列号", value: "serialNumber"},
  {label: "MAC地址", value: "macAddress"},
  {label: "设备品牌", value: "deviceBrand"},
  {label: "设备型号", value: "deviceModel"},
  // {label: "设备型号", value: "deviceModel"},
  // {label: "投放点名称", value: "deviceName"},
  // {label: "辖区", value: "areaName"},
  // {label: "街道", value: "streetName"},
  // {label: "社区", value: "community"},

])

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deviceBrand: null,
    deviceModel: null,
    deviceStatus: null,
    deviceName: null,
    serialNumber: null,
    proviceName: null,
    proviceCode: null,
    cityName: null,
    cityCode: null,
    areaName: null,
    areaCode: null,
    address: null,
    community: null,
    residentialName: null,
    ip: null,
    macAddress: null,
    placement: null,
    registerTime: null,
    accessStatus: null,
    accessTime: null,
    streetName: null,
    streetCode: null
  },
});

const {queryParams, rules} = toRefs(data);

/** 查询读卡器列表 */
function getList() {
  loading.value = true;
  if(singleSearch.value) {
    proxy.resetForm("queryRef");
    queryParams.value[queryParamsSearch.value.key]=queryParamsSearch.value.keyWord;
  }
  listCardReader(queryParams.value).then(response => {
    cardReaderList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

function changeKeyType(){
  queryParamsSearch.value.keyWord=''
  resetMyForm();
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  resetMyForm();
  if(singleSearch.value){
    queryParamsSearch.value.key='serialNumber';
    queryParamsSearch.value.keyWord=''
  }
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}


/** 新增按钮操作 */
function handleAdd() {

  pluginFormRef.value.begin(false);
}


/** 修改按钮操作 */
function handleUpdate(row) {
  const _id = row.id || ids.value
  pluginFormRef.value.begin(_id)
}

// 关闭刷新页面
function close(reset = false) {
  if (reset) {
    resetQuery()
  } else {
    getList()
  }
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除读卡器编号为"' + _ids + '"的数据项？').then(function () {
    return delCardReader(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}


/** 导出按钮操作 */
function handleExport() {
  proxy.download('wvp/cardReader/export', {
    ...queryParams.value
  }, `读卡器_${new Date().getTime()}.xlsx`)
}

getList();


const screenHeight = ref(window.innerHeight);
const tableHeight = ref(10);
const tableRef = ref();

function handleResize() {
  screenHeight.value = window.innerHeight;
  tableHeight.value = screenHeight.value - tableRef.value.$el.getBoundingClientRect().top - 80;
}

onMounted(() => {
  handleResize()
  window.addEventListener('resize', handleResize);
});
onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
});


const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: {Authorization: "Bearer " + getToken()},
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/wvp/cardReader/importData"
});

/** 导入按钮操作 */
function handleImport() {
  upload.title = "读卡器导入";
  upload.open = true;
};

/** 下载模板操作 */
function importTemplate() {
  proxy.download("wvp/cardReader/importTemplate", {}, `读卡器导入模板_${new Date().getTime()}.xlsx`);
};
/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", {dangerouslyUseHTMLString: true});
  getList();
};

/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
};


function changePushType(row) {
  updateCardReader(Object.assign({}, {id: row.id, pushType: row.pushType})).then(res => {
  })
}

const pushTypeForm = ref({
  ids: [],
  pushType: 0
})
const showPushTypeForm = ref(false)

function beginPushType() {
  if(ids.value < 1){
    proxy.$modal.msgWarning("请勾选需要操作的数据")
    return;
  }
  showPushTypeForm.value = true;
  pushTypeForm.value.ids=ids.value;
  pushTypeForm.value.pushType=0;
}
function submitPushTypeFormHandle(){
  submitPushTypeForm(pushTypeForm.value).then(res=>{
    proxy.$modal.msgSuccess("操作成功")
    showPushTypeForm.value=false;
    getList();
  })
}
</script>
<style scoped lang="scss">
.pagination-container {
  margin-top: 0 !important;

  .el-pagination {
    right: 40px !important;

  }
}

</style>
